# -*- encoding=utf8 -*-

import os
import sys
import re

print(
    """
参数说明(默认为1)：
    1 - gitee
    2 - gitlab
    3 - github
****************************************
"""
)

URL_GITEE = "https://gitee.com/Andney/CTPods.git"
URL_GITLAB = "http://gitlab.ctwenhuayun.cn/cocoapods/CTPods.git"
URL_GITHUB = "https://github.com/Andney/CTPods.git"
URL_LIST = [URL_GITEE, URL_GITLAB, URL_GITHUB]

# 提取git地址的正则
REGEX_GET_GIT_PATH = r'^\s+\"git\":\s+\"([^"]*)\",[\s]*$'
# 替换git地址的正则
REGEX_REPLACE_GIT_PATH = r'^(\s+\"git\":\s+)\"([^"]*)\",$'


def ct_updatePodspecSource(path, gitSrcPath):
    """更新podspec文件的git仓库地址"""

    if not os.path.exists(path):
        print("The file '{0}' is not existed.".format(path))
        return None
    try:
        with open(path, "r") as f:
            file_contents = ""
            has_changed = False
            # 逐行读取文件内容
            for line in f.readlines():
                if line.strip().startswith('"git"'):
                    # 提取原有的git仓库地址
                    gitPath = re.sub(REGEX_GET_GIT_PATH, "\\1", line)

                    if gitPath != gitSrcPath and gitPath in URL_LIST:
                        # 替换新的git仓库地址
                        file_contents += re.sub(
                            REGEX_REPLACE_GIT_PATH, '\\1"{0}",'.format(gitSrcPath), line
                        )
                        has_changed = True
                    else:
                        file_contents += line
                else:
                    file_contents += line

            f.close()

            if has_changed:
                # 写入文件
                with open(path, "w") as f:
                    f.write(file_contents)
                    f.close()
                    print("仓库源地址已更换: {0}".format(path))
                    return True

    except OSError as error:
        print(error)

    return False


def ct_enumFiles(folder, pathExtension, callback):
    """枚举文件\n
    Args:
        folder: 文件夹路径
        pathExtension: 文件后缀，包含“.”
        callback: 回调函数，每次匹配到文件后，均会回调
    """

    try:
        for item in os.listdir(folder):
            tmp_path = os.path.join(folder, item)
            if os.path.isdir(tmp_path):
                ct_enumFiles(tmp_path, pathExtension, callback)
            elif os.path.isfile(tmp_path) and item.endswith(pathExtension):
                callback(item, tmp_path)
    except Exception as err:
        print(err)


def ct_switchPodspecSource(fileName, path):
    """切换git仓库源\n
    Args:
        fileName: podspec文件名
        path: podspec文件路径
    """
    ct_updatePodspecSource(path, git_url)


git_url = ""
if len(sys.argv) > 1:
    a = sys.argv[1]
    if a == "1":
        git_url = URL_GITEE
    elif a == "2":
        git_url = URL_GITLAB
    elif a == "3":
        git_url = URL_GITHUB
    else:
        sys.exit("参数错误（只能选择：1、2、3）")
else:
    git_url = URL_GITEE

root_specs_fold = "../Specs"
ct_enumFiles(root_specs_fold, ".podspec.json", ct_switchPodspecSource)